package com.wycdrive.nyc.model.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class JsonUtils {
    private static volatile Gson gson;
    private static volatile Gson outGson;

    private JsonUtils() {

    }

    public static Gson getGI() {
        if (gson == null) {
            synchronized (JsonUtils.class) {
                if (gson == null) {
                    gson =  new GsonBuilder()
                            .setLenient()
                            .serializeNulls()
                            .create();
                }
            }
        }
        return gson;
    }

    public static Gson outGI() {
        if (outGson == null) {
            synchronized (JsonUtils.class) {
                if (outGson == null) {
                    outGson = new GsonBuilder()
                            .excludeFieldsWithoutExposeAnnotation()
                            .serializeNulls()
                            .create();
                }
            }
        }
        return outGson;
    }

    /**
     * 解析 Hashmap list
     *
     * @param str
     * @return
     */
    public static HashMap<String, String> parse2HashMap(String str) {
        return getGI().fromJson(str, new TypeToken<HashMap<String, String>>() {
        }.getType());
    }

    /**
     * 解析对象
     *
     * @param <T>
     * @param str
     * @param c
     * @return
     */
    public static <T> T parse2Obj(String str, Class<T> c){
        T t = null;
        try {
            t = getGI().fromJson(str, c);
        } catch (com.google.gson.JsonSyntaxException e) {
            e.printStackTrace();
        }
        return t;
    }


    /**
     * 解析对象
     *
     * @param str
     * @return
     */
    public static String parse2String(String str) {
        JSONObject obj;
        try {
            obj = new JSONObject(str);
            return obj.getString("o");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "0";
    }


//    public static HashMap<String, Object> toJsonParams(HashMap<String, Object> hashmap) {
//        HashMap<String, Object> jsonparams = new HashMap<String, Object>();
//        jsonparams.put("json", outGI().toJson(hashmap));
//        //REMOVE LOG"framework", jsonparams.toString());
//        return jsonparams;
//    }

    public static String toJsonParams(Object object) {
        return outGI().toJson(object);
    }


}
